import React, { useState, useEffect } from "react";
import ModelChat from './modules/ModelChat';
import { fetchChat } from '@/service/api/chat'; // 引入通用的 fetchChat 函数
import { fetchWenxinToken } from '@/service/api/get_wenxin_access';  // 引入获取 token 的函数
import { Modal, Input, Button, notification, Spin, Row, Col } from 'antd';  // 引入 Spin
export function Component() {
  const [allAtOnce, setAllAtOnce] = useState<boolean>(false);
  const [models, setModels] = useState<any[]>([
    { name: "ernie", enabled: true, messages: [{ model: "ernie", role: "system", content: "Welcome to WenXin! How can I assist you today?" }] },
    { name: "openai", enabled: true, messages: [{ model: "openai", role: "system", content: "Hello! I'm OpenAI. How can I help?" }] },
    { name: "deepseek", enabled: true, messages: [{ model: "deepseek", role: "system", content: "Hi! DeepSeek is ready to chat!" }] },
  ]);

  const [apiKey, setApiKey] = useState<string>(''); // Wenxin API Key
  const [secretKey, setSecretKey] = useState<string>(''); // Wenxin Secret Key
  const [openaiApiKey, setOpenaiApiKey] = useState<string>(''); // OpenAI API Key
  const [deepseekApiKey, setDeepseekApiKey] = useState<string>(''); // DeepSeek API Key
  const [accessToken, setAccessToken] = useState<string | null>(null); // 存储获取到的 Access Token
  const [modalVisible, setModalVisible] = useState<boolean>(false); // 控制 Modal 的显示
  const [missingTokens, setMissingTokens] = useState<string[]>([]); // 存储缺失的 Token
  const [loading, setLoading] = useState<boolean>(false);  // 添加 loading 状态

  // 页面加载时校验缓存
  useEffect(() => {
    const cachedToken = localStorage.getItem('wenxin_access_token');
    const cachedOpenaiToken = localStorage.getItem('openai_api_key');
    const cachedDeepseekToken = localStorage.getItem('deepseek_api_key');
    setOpenaiApiKey(cachedOpenaiToken || '');
    setDeepseekApiKey(cachedDeepseekToken || '');
    let missing = [];

    if (cachedToken) {
      setAccessToken(cachedToken);
      console.log('Using cached access token:', cachedToken);
    } else {
      missing.push('wenxin');
    }

    if (!cachedOpenaiToken) {
      missing.push('openai');
    }

    if (!cachedDeepseekToken) {
      missing.push('deepseek');
    }

    if (missing.length > 0) {
      setMissingTokens(missing);
      setModalVisible(true); // 显示 Modal 提示用户输入缺失的 Token
    }

  }, []);

  const sendMessage = (type: string, payload: { model: string; enabled: boolean }) => {
    if (type === 'toggle') {
      setModels(models.map((model) =>
        model.name === payload.model ? { ...model, enabled: payload.enabled } : model
      ));
    }
    console.log(models, 'models')
  };

  // 根据启用状态对模型排序：启用的排在前，禁用的排在后
  const sortedModels = models.sort((a, b) => {
    if (a.enabled && !b.enabled) return -1;
    if (!a.enabled && b.enabled) return 1;
    return 0;
  });


  // 分组禁用状态的模型，每组两个
  const groupedDisabledModels = [] as any;
  let tempGroup = [] as any;
  sortedModels.forEach((model, index) => {
    console.log(model)
    if (!model.enabled) {
      tempGroup.push(model);
      if (tempGroup.length === 2 || index === sortedModels.length - 1) {
        groupedDisabledModels.push(tempGroup);
        tempGroup = [];
      }
    } else {
      if (tempGroup.length > 0) {
        groupedDisabledModels.push(tempGroup);
        tempGroup = [];
      }
      groupedDisabledModels.push([model]);
    }
  });


  // 计算禁用模型的列宽
  const getDisabledCols = (disabledCount: number) => {
    console.log(disabledCount)
    if (disabledCount <= 1) return { xs: 24, sm: 12, md: 24, lg: 24 }; // 每个占一半宽度
    if (disabledCount <= 2) return { xs: 24, sm: 12, md: 12, lg: 12 }; // 每个占一半宽度
    if (disabledCount <= 3) return { xs: 24, sm: 12, md: 8, lg: 8 };  // 每个占三分之一宽度
    return { xs: 24, sm: 12, md: 6, lg: 6 }; // 每个占四分之一宽度
  };


  const handleSendMessage = async (assistantMessage: { model: string; text: string }) => {
    // 动态构建选中的模型数组
    const selectedModels = models.filter(model => model.enabled).map(model => model.name);

    console.log('Selected Models:', selectedModels);  // 确保这是一个包含所有选中模型的数组

    setLoading(true); // 开始加载

    try {
      // 修改为支持多选模型
      const promises = selectedModels.map(async (model) => {
        assistantMessage.model = model;

        // 处理 Wenxin 模型
        if (model === 'ernie' && accessToken) {
          const chatResponse = await fetchChat([model], assistantMessage.text, accessToken);
          return { model, content: chatResponse?.data?.find(item => item.model === model)?.response || 'No response from model' };
        }
        // 处理 OpenAI 模型
        if (model === 'openai' && openaiApiKey) {
          const chatResponse = await fetchChat([model], assistantMessage.text, openaiApiKey);
          return { model, content: chatResponse?.data?.find(item => item.model === model)?.response || 'No response from model' };
        }

        // 处理 DeepSeek 模型
        if (model === 'deepseek' && deepseekApiKey) {
          const chatResponse = await fetchChat([model], assistantMessage.text, deepseekApiKey);
          return { model, content: chatResponse?.data?.find(item => item.model === model)?.response || 'No response from model' };
        }

        return { model, content: 'No valid API key available for this model' };
      });

      // 等待所有模型的响应
      const responses = await Promise.all(promises);

      // 更新状态，格式化消息为 { model, role, content } 结构
      setModels(prevModels =>
        prevModels.map(model => {
          if (model.enabled && selectedModels.includes(model.name)) {
            const modelResponse = responses.find(response => response.model === model.name);
            if (modelResponse) {
              return {
                ...model,
                messages: [...model.messages, { model: model.name, role: 'assistant', content: modelResponse.content }]
              };
            }
          }
          return model;
        })
      );

    } catch (error) {
      console.error('Error calling model API:', error);
    } finally {
      setLoading(false);  // 请求结束，关闭加载状态
    }
  };


  const handleSubmitToken = async () => {
    // 如果 Wenxin API Key 和 Secret Key 为空，直接提示
    console.log((!apiKey || !secretKey) && !accessToken)
    if ((!apiKey || !secretKey) && !accessToken) {
      console.log('API Key and Secret Key are required for Wenxin')
      return;
    }
    console.log(!accessToken)
    if (!accessToken) {
      try {
        // 获取 Wenxin 的 Access Token
        const response = await fetchWenxinToken(apiKey, secretKey);
        if (response?.data?.access_token) {
          // 获取到 Wenxin token 后存入缓存并更新状态
          localStorage.setItem('wenxin_access_token', response.data.access_token);
          setAccessToken(response.data.access_token);
          console.log('Fetched new Wenxin access token:', response.data.access_token);
        } else {
          notification.error({
            message: 'Error',
            description: 'Failed to get Wenxin access token',
          });
        }
      } catch (error) {
        console.error('Error fetching Wenxin access token:', error);
        notification.error({
          message: 'Error',
          description: 'Failed to fetch Wenxin access token. Please try again.',
        });
        return; // 在此处添加返回，防止后续的代码执行
      }
    }



    // 检查 OpenAI 和 DeepSeek 的 API Key 是否已保存
    if (!openaiApiKey || !deepseekApiKey) {
      console.log('OpenAI and DeepSeek API Keys are required')
      return;
    }

    // 保存 OpenAI 和 DeepSeek 的 API Key 到缓存
    localStorage.setItem('openai_api_key', openaiApiKey);
    localStorage.setItem('deepseek_api_key', deepseekApiKey);
    console.log('Saved OpenAI and DeepSeek API Keys to localStorage');

    // 检查是否所有的 Token 都已经存储并关闭弹窗
    const cachedToken = localStorage.getItem('wenxin_access_token');
    const cachedOpenaiToken = localStorage.getItem('openai_api_key');
    const cachedDeepseekToken = localStorage.getItem('deepseek_api_key');

    if (cachedToken && cachedOpenaiToken && cachedDeepseekToken) {
      setModalVisible(false); // 所有密钥存在时，关闭弹窗
    }
  };


  const handleResetApiKey = (model: string) => {
    if (model === 'ernie') {
      setAccessToken('');  // 清空 Wenxin Access Token
      localStorage.removeItem('wenxin_access_token');  // 从 localStorage 删除
    } else if (model === 'openai') {
      setOpenaiApiKey('');  // 清空 OpenAI API Key
      localStorage.removeItem('openai_api_key');  // 从 localStorage 删除
    } else if (model === 'deepseek') {
      setDeepseekApiKey('');  // 清空 DeepSeek API Key
      localStorage.removeItem('deepseek_api_key');  // 从 localStorage 删除
    }
    notification.info({
      message: 'API Key Reset',
      description: `${model === 'ernie' ? '文心一言' : model === 'openai' ? 'OpenAI' : 'DeepSeek'} API Key has been reset.`,
    });
  };

  return (
    <div style={{ alignItems: "left" }}>
      {/* 加载中效果 */}
      {loading && (
        <div style={{ display: 'flex', justifyContent: 'center', marginTop: '20px' }}>
          <Spin size="large" />
        </div>
      )}

      {/* Left Top: Display Access Token */}
      <div>
        <label style={{ marginRight: 10 }}>文心一言 Access Token:</label>
        <Input
          value={accessToken || 'Not Set'}
          style={{ width: 300 }}
          readOnly={true}
          placeholder="文心一言 Access Token"
        />
        {accessToken && (
          <Button type="primary" onClick={() => handleResetApiKey('ernie')} style={{ marginLeft: 10 }}>
            重置
          </Button>
        )}
      </div>

      {/* Display OpenAI and DeepSeek API Keys */}
      <div style={{ marginRight: 10, marginTop: 10, }}>
        <label style={{ marginRight: 10, marginTop: 10, }}>OpenAI API Key:</label>
        <Input
          value={openaiApiKey || 'Not Set'}
          style={{ width: 300 }}
          readOnly={true}
          placeholder="OpenAI API Key"
        />
        {openaiApiKey && (
          <Button type="primary" onClick={() => handleResetApiKey('openai')} style={{ marginLeft: 10 }}>
            重置
          </Button>
        )}
      </div>
      <div style={{ marginRight: 10, marginTop: 10, marginBottom: 20, }}>
        <label style={{ marginRight: 10, marginTop: 10, }}>DeepSeek API Key:</label>
        <Input
          value={deepseekApiKey || 'Not Set'}
          style={{ width: 300 }}
          readOnly={true}
          placeholder="DeepSeek API Key"
        />
        {deepseekApiKey && (
          <Button type="primary" onClick={() => handleResetApiKey('deepseek')} style={{ marginLeft: 10 }}>
            重置
          </Button>
        )}
      </div>

      {/* Send to Selected Models */}
      <div style={{ marginRight: "10px", color: "white", float: 'right' }}>
        {/* 全选按钮 */}
        <Button
          onClick={() => {
            const newEnabledState = !models.every(model => model.enabled); // 切换所有模型启用状态
            setModels(models.map(model => ({ ...model, enabled: newEnabledState })));
          }}
        >
          {models.every(model => model.enabled) ? '取消全选' : '全选'}
        </Button>
      </div>

      {/* Display Models */}
      <div style={{ display: "flex", flexDirection: "column", alignItems: "center" }}>
        <div style={{ display: "flex", gap: "20px", flexWrap: "wrap", justifyContent: "center" }}>
          <ARow gutter={[16, 16]}>
            {/* 显示启用的模型 */}
            {sortedModels.filter(i => i.enabled === true).length > 0 && (
              <Row gutter={[16, 16]} style={{ flexWrap: 'wrap', marginTop: '20px' }}>
                {sortedModels.filter(i => i.enabled === true).map(({ name, enabled, messages }) => (
                  <Col {...getDisabledCols(sortedModels.filter(i => i.enabled === true).length)} key={name}>
                  <ModelChat
                    key={name}
                    model={name}
                    enabled={enabled}
                    sendMessage={sendMessage}
                    allAtOnce={allAtOnce}
                    onSendMessage={(assistantMessage) => handleSendMessage(assistantMessage)}
                    messages={messages?.map((msg: { model: any; role: any; content: any; }) => ({
                      model: msg.model,
                      role: msg.role,
                      content: msg.content,
                    }))}
                  />
                </Col>
                ))}
              </Row>
            )}
          </ARow>
        </div>
        <div style={{ display: "flex", gap: "20px", flexWrap: "wrap", justifyContent: "center" }}>
          {/* 新的一行，用于禁用的模型 */}
          <ARow gutter={[16, 16]}>
            {/* 显示禁用的模型并强制换行 */}
            {sortedModels.filter(i => i.enabled === false).length > 0 && (
              <Row gutter={[16, 16]} style={{ flexWrap: 'wrap', marginTop: '20px' }}>
                {/* 显示禁用的模型并强制换行 */}
                {sortedModels.filter(i => i.enabled === false).map(({ name, enabled, messages }) => (
                  <Col {...getDisabledCols(sortedModels.filter(i => i.enabled === false).length)} key={name}>
                    <ModelChat
                      model={name}
                      enabled={enabled}
                      sendMessage={sendMessage}
                      allAtOnce={allAtOnce}
                      onSendMessage={(assistantMessage) => handleSendMessage(assistantMessage)}
                      messages={messages?.map((msg: { model: any; role: any; content: any; }) => ({
                        model: msg.model,
                        role: msg.role,
                        content: msg.content,
                      }))}
                    />
                  </Col>
                ))}
              </Row>
            )}

          </ARow>
        </div>
      </div >

      {/* Modal to submit missing API tokens */}
      < Modal
        title="Missing API Keys"
        open={modalVisible}
        onOk={handleSubmitToken}
        onCancel={() => setModalVisible(false)
        }
      >
        <div>
          <p>Missing Tokens: {missingTokens.join(', ')}</p>

          {/* Wenxin API Key 输入框 */}
          <div>
            <label htmlFor="apiKey">Wenxin API Key</label>
            <Input
              id="apiKey"
              value={apiKey}
              onChange={(e) => setApiKey(e.target.value)}
              placeholder="Enter Wenxin API Key"
            />
          </div>

          {/* Wenxin Secret Key 输入框 */}
          <div>
            <label htmlFor="secretKey">Wenxin Secret Key</label>
            <Input
              id="secretKey"
              value={secretKey}
              onChange={(e) => setSecretKey(e.target.value)}
              placeholder="Enter Wenxin Secret Key"
            />
          </div>

          {/* OpenAI API Key 输入框 */}
          <div>
            <label htmlFor="openaiApiKey">OpenAI API Key</label>
            <Input
              id="openaiApiKey"
              value={openaiApiKey}
              onChange={(e) => setOpenaiApiKey(e.target.value)}
              placeholder="Enter OpenAI API Key"
            />
          </div>

          {/* DeepSeek API Key 输入框 */}
          <div>
            <label htmlFor="deepseekApiKey">DeepSeek API Key</label>
            <Input
              id="deepseekApiKey"
              value={deepseekApiKey}
              onChange={(e) => setDeepseekApiKey(e.target.value)}
              placeholder="Enter DeepSeek API Key"
            />
          </div>
        </div>
      </Modal >

    </div >
  );
}
